package com.carb.handler;

import com.carb.constant.MessageConstant;
import com.carb.exception.BaseException;
import com.carb.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLSyntaxErrorException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param e 业务异常
     * @return 异常信息
     */
    @ExceptionHandler
    public Result<String> exceptionHandler(BaseException e){
        log.error("异常信息：{}", e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 处理SQL完整性约束冲突异常
     * @param e SQL完整性约束冲突异常
     * @return 异常信息
     */
    @ExceptionHandler
    public Result<String> SQLIntegrityConstraintViolationExceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error("SQL完整性约束冲突异常：{}", e.getMessage());
        // Duplicate entry 'member004' for key 'tb_user.username'
        String message = e.getMessage();
        if (message.contains("Duplicate entry")) {
            String entryName = message.split(" ")[2];
            String errorMessage = entryName + MessageConstant.ALREADY_EXISTS;
            return Result.error(errorMessage);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 处理SQL语法错误异常
     * @param e SQL语法错误异常
     * @return 异常信息
     */
    @ExceptionHandler
    public Result<String> SQLSyntaxErrorExceptionHandler(SQLSyntaxErrorException e) {
        log.error("SQL语法错误异常：{}", e.getMessage());
        // Unknown column 'projectId' in 'order clause'
        String message = e.getMessage();
        if (message.contains("Unknown column")) {
            String columnName = message.split(" ")[2];
            String errorMessage = columnName + MessageConstant.COLUMN_ERROR;
            return Result.error(errorMessage);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 处理JSON解析异常
     * @param e JSON反序列化异常
     * @return 异常信息
     */
    @ExceptionHandler
    public Result<String> HttpMessageNotReadableExceptionHandler(HttpMessageNotReadableException e) {
        log.error("JSON解析异常信息：{}", e.getMessage());
        // JSON parse error: Cannot deserialize
        String message = e.getMessage();
        if (message.contains("JSON parse error")) {
            String param = message.split(":")[1].trim().split(" ")[8].replace("\"", "'");
            String errorMessage = MessageConstant.ILLEGAL_PARAM + param;
            return Result.error(errorMessage);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 处理SQL字段无默认值异常
     * @param e SQL异常
     * @return 异常信息
     */
    @ExceptionHandler
    public Result<String> SQLExceptionHandler(SQLException e) {
        log.error("SQL异常：{}", e.getMessage());
        // Field 'username' doesn't have a default value
        String message = e.getMessage();
        if (message.contains("doesn't have a default value")) {
            return Result.error(MessageConstant.INCOMPLETE_INFORMATION);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
